package com.zhijiaoyun.controller.api;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zhijiaoyun.model.CourseHistory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alipay.api.AlipayApiException;
import com.alipay.api.domain.AlipayTradePayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.zhijiaoyun.alipay.AlipayConfig;
import com.zhijiaoyun.common.StringUtils;
import com.zhijiaoyun.controller.base.BaseController;
import com.zhijiaoyun.model.BuyHistory;
import com.zhijiaoyun.model.Order;
import com.zhijiaoyun.model.OrderDetail;

/**
 * @author shisfish
 * @date 2017/6/6
 */
@Controller
@RequestMapping(value = "/api/alipay")
public class AlipayApi  extends BaseController{
	
	@ResponseBody
	@RequestMapping(value = "/tradepay",  method = RequestMethod.GET)
	public void tradepay(HttpServletRequest httpRequest,
            HttpServletResponse httpResponse, String orderNum) {
		AlipayTradePayModel model = orderService.getAlipayTradePayModelByOrderNum(orderNum);
		AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
		request.setReturnUrl(AlipayConfig.RETURN_URL);
		request.setNotifyUrl(AlipayConfig.NOTIFY_URL);
		request.setBizModel(model);
		AlipayTradePagePayResponse response;
		try {
			response = AlipayConfig.alipayClient.pageExecute(request);
			if(response.isSuccess()){
			    httpResponse.setContentType("text/html;charset=UTF-8");
			    //直接将完整的表单html输出到页面
			    httpResponse.getWriter().write(response.getBody());
			    //httpResponse.getWriter().flush();
			    httpResponse.getWriter().close();
			} else {
				System.out.println(response.getMsg());
			}
		} catch (AlipayApiException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@ResponseBody
	@RequestMapping(value = "/notifyUrl",  method = RequestMethod.POST)
	public void notifyUrl(HttpServletRequest request, HttpServletResponse response) throws IOException{
		try {
			Map<String,String> params = AlipayConfig.toMap(request);
			
			boolean verifyResult = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET,
					AlipayConfig.SIGN_TYPE);
			// 验证成功
			if (verifyResult) {
				String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
				Order order = orderService.getOrderByOrderNum(out_trade_no);
				if (order != null && order.getStatus() != 2) {
					List<OrderDetail> details = orderDetailService.getOrderDetailByOrderNum(out_trade_no);
					if (!StringUtils.isEmptyList(details)) {
						for (OrderDetail orderDetail : details) {
							BuyHistory buy = buyHistoryService.getBuyHistoryByUserIdGoodsId(orderDetail.getUserId(),
									orderDetail.getGoodsId(), orderDetail.getGoodsType());
							if (buy == null) {
								BuyHistory buy1 = new BuyHistory(orderDetail.getUserId(), orderDetail.getGoodsId(),
										orderDetail.getGoodsType());
								buyHistoryService.addBuyService(buy1);
								// 商品的购买记录+1
								if (buy1.getGoodsType() == 1) {
									courseService.addSaleNum(buy1.getGoodsId());
								}
							}
							CourseHistory courseHistory = courseHistoryService.getCourseHistoryByCourseIdUserId(orderDetail.getGoodsId(), orderDetail.getUserId());
							if (courseHistory == null) {
								courseHistory = new CourseHistory(orderDetail.getUserId(), orderDetail.getGoodsId(), 1, 0D);
								courseHistoryService.addCourseHistory(courseHistory);
							}
						}
					}
					order.setStatus(2);
					orderService.modifyOrder(order);
				}
				System.out.println("notifySuccess");
			    PrintWriter out = response.getWriter();
				out.print("success");
				out.flush();
				out.close();
            } else {
            	System.out.println("notifyError");
                PrintWriter out = response.getWriter();
				out.print("error");
				out.flush();
				out.close();
            }
		} catch (AlipayApiException e) {
			e.printStackTrace();
			System.out.println("notifyError");
		}
	}
	
	@ResponseBody
	@RequestMapping(value = "/returnUrl",  method = RequestMethod.GET)
	public void returnUrl(HttpServletRequest request, HttpServletResponse httpResponse) throws IOException{
		// 只有成功才会返回该地址
		String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
	    Order order = orderService.getOrderByOrderNum(out_trade_no);
	    if (order != null) {
	    	List<OrderDetail> details = orderDetailService.getOrderDetailByOrderNum(out_trade_no);
			if (!StringUtils.isEmptyList(details)) {
				for (OrderDetail orderDetail : details) {
					BuyHistory buy = buyHistoryService.getBuyHistoryByUserIdGoodsId(orderDetail.getUserId(),
							orderDetail.getGoodsId(), orderDetail.getGoodsType());
					if (buy == null) {
						BuyHistory buy1 = new BuyHistory(orderDetail.getUserId(), orderDetail.getGoodsId(),
								orderDetail.getGoodsType());
						buyHistoryService.addBuyService(buy1);
						// 商品的购买记录+1
						if (buy1.getGoodsType() == 1) {
							courseService.addSaleNum(buy1.getGoodsId());
						}
					}
					CourseHistory courseHistory = courseHistoryService.getCourseHistoryByCourseIdUserId(orderDetail.getGoodsId(), orderDetail.getUserId());
					if (courseHistory == null) {
						courseHistory = new CourseHistory(orderDetail.getUserId(), orderDetail.getGoodsId(), 1, 0D);
						courseHistoryService.addCourseHistory(courseHistory);
					}
				}
			}
			order.setStatus(2);
			orderService.modifyOrder(order);
		}
	    System.out.println("returnSuccess");
	    httpResponse.sendRedirect("http://www.zhijiaolearn.com/zhijiaoyun/#/order-center");
	}
}